/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */
"use strict";
let api = require('../../utils/api');
const sha1 = require('sha1');
const extend = require('extend');
const md5 = require('md5');
// const SERVER_URL = "gy.rechange.cn";
const SERVER_URL = "www.kycozyhome.com";

module.exports = {

    index: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('557f439234g4f323f909k37c70d3c25c'),
            json: {
                properties: {
                    // recommend: true,
                    // apartment_city_obj_ae: '001',
                    // status: 1,
                    // pageSize: 9999
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            console.log("----------------------------22-----------------------");
            console.log({houseList: data});
            console.log("---------------------------333------------------------");
            callback({houseList: data}, global.config.permission.public, response);
        });
    },

    rule: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('369cf93b979a4569887d3839b806b0fd').replace('{id}', req.query.id)
        }, function (error, response, body) {
            let data = body && body.value;
            callback(data || [], global.config.permission.public, response);
        });
    },

    houseSearch: function (req, res, callback, next) {
        if (req.query.groupFlag) {
            global.tool.send({
                method: 'post',
                uri: api.get('557583907a244d1d90fc237c70d3c25c'),
                json: {
                    properties: {
                        apartment_city_obj_ae: req.query.city || '001',
                        // status: 1,
                        // pageSize: 50
                    }
                }
            }, function (error, response, body) {

                Promise.all(global.tool.getEnumsByCodes(['cityList', 'houseType'])).then(function (data) {
                    let row = (body && body.rows) || [];
                    var result = global.tool.extend({houseList: row}, global.tool.extend({cityList: data[0]}, {houseType: data[1]}));
                    callback(result, global.config.permission.public, response);
                });

            });
        } else {
            global.tool.send({
                method: 'post',
                uri: api.get('9651431c68a04d54a22f1e2e7faf827b'),
                json: {
                    properties: {
                        apartment_city_obj_ae: req.query.city || '001',
                        status: 1,
                        pageSize: 50
                    }
                }
            }, function (error, response, body) {
                let row = (body && body.rows) || [];
                callback({houseList: row}, global.config.permission.public, response);
            });
        }

    },

    account: function (req, res, callback) {
        if (req.session.userData) {
            console.log('req.session.userData.id : ' + req.session.userData.id);
            global.tool.send({
                method: 'get',
                uri: api.get('5b90151b418f4ceb9469a6b265b0d617').replace(new RegExp('{id}'), req.session.userData.id)
            }, function (error, response, body) {
                let data = body && body.value;
                // console.log('req.session.userData.status : '+req.session.userData.status);
                // console.log('data.status : '+data.status);
                console.log(data);
                if (data != null) {
                    req.session.userData.status = data.status;
                    req.session.userData.userType = data.userType;
                }
                callback(data, global.config.permission.private, response);
            });
        } else {
            callback({}, global.config.permission.private, response);
        }
    },

    news: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('c97b00aa70fc4ed1b5922bced4468a0b'),
            json: {
                properties: {
                    model_code_obj_ae: req.query.modelCode || 'kynews',
                    pageSize: 7
                }
            }
        }, function (error, response, body) {
            let data = body && body.rows;
            callback(data || [], global.config.permission.public, response);
        });
    },

    newsDetail: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('369cf93b979a4569887d3839b806b0fd').replace('{id}', req.query.id)
        }, function (error, response, body) {
            let data = body && body.value;
            callback(data || [], global.config.permission.public, response);
        });
    },

    ytInfo: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('369cf93b979a4569887d3839b806b0fd').replace('{id}', req.query.id)
        }, function (error, response, body) {
            let data = body && body.value;
            callback(data || [], global.config.permission.public, response);
        });
    },

    houseInfo: function (req, res, callback, next) {
        if (req.query.groupFlag) {
            global.tool.send({
                method: 'get',
                uri: api.get('0ce999a04d57409f8abd6297ece1fbcd') + '?houseGroup=' + req.query.houseGroup + '&apartmentCity=' + req.query.apartmentCity
            }, function (error, response, body) {
                let data = (body && body.value) || {};

                let url = "url=http://" + SERVER_URL + "/yams/view/houseInfo?groupFlag=" + req.query.groupFlag+"&apartmentCity="+req.query.apartmentCity+"&houseGroup="+req.query.houseGroup;
                let t = new Date().getTime();
                global.weChatUtil.getTicket(function (ticket) {
                    let key = [];
                    key.push("jsapi_ticket=" + ticket);
                    key.push("noncestr=a" + t);
                    key.push("timestamp=" + t);
                    key.push(url);
                    let str = sha1(key.join("&"));
                    console.log(key.join("&"), str);
                    extend(data, {
                        appId: global.weChatUtil.config.appid,
                        timestamp: t,
                        nonceStr: "a" + t,
                        signature: str
                    });
                    console.log("111////////////////////////////////////////////////////")
                    console.log(data);
                    console.log("111////////////////////////////////////////////////////")
                    callback(data, global.config.permission.private, response);
                });
            });
        } else {
            global.tool.send({
                method: 'get',
                uri: api.get('319bc41c5fe44dfc9f396b5ace5faf4a').replace("{id}", req.query.id)
            }, function (error, response, body) {
                let data = (body && body.value) || {};
                console.log("////////////////////////////////////////////////////")
                console.log(data);
                console.log("////////////////////////////////////////////////////")
                callback(data, global.config.permission.public, response);
            });
        }

    },

    houseReserved: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('319bc41c5fe44dfc9f396b5ace5faf4a').replace("{id}", req.query.houseId)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.public, response);
        });
    },

    order: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('00923c89a610415d8e70b1b4f2380e75'),
            json: {
                properties: {
                    user_code_obj_ae: req.session.userData.code
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },

    myShortRent: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('f266ff4abe8d42bcb86931f7acc827be'),
            json: {
                properties: {
                    user_id_obj_ae: req.session.userData.id
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },

    contract: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('509cb2a903d2466b9645432e025609c4'),
            json: {
                properties: {
                    user_id_obj_ae: req.session.userData.id
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },

    contractInfo: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('ae5b4154f12b4ad5a074eaefec3b47bb').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.private, response);
        });
    },

    contractDetail: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('ae5b4154f12b4ad5a074eaefec3b47bb').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.private, response);
        });
    },

    bill: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('4bd717c1cca5449a8a82c1b1584f87d3'),
            json: {
                properties: {
                    user_id_obj_ae: req.session.userData.id
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },

    toPayBill: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('4bd717c1cca5449a8a82c1b1584f87d3'),
            json: {
                properties: {
                    user_id_obj_ae: req.session.userData.id,
                    status: 0
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },
    //账单支付
    wepay: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('0ab39b2ab218459c9d48d91246742d68').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            console.log("----------data----------");
            console.log(data);
            global.weChatUtil.preOrder({
                nonce_str: data.code,
                amount: data.actualAmount,
                remoteIp: req.get('X-Real-IP') || req.get('x-real-ip'),
                openid: req.session.userData.weChat,
                siteId: 'mine'
            }, function (ret) {
                if (ret.return_code === 'SUCCESS') {
                    global.weChatUtil.getTicket(function (ticket) {
                        let key = [], n = new Date().getTime();
                        key.push("jsapi_ticket=" + ticket);
                        key.push("noncestr=" + data.code);
                        key.push("timestamp=" + n);
                        key.push("url=http://" + SERVER_URL + "/view/order/wepay?id=" + data.id);
                        let str = sha1(key.join("&"));
                        let paySign = [];
                        paySign.push("appId=" + ret.appid);
                        paySign.push("nonceStr=" + data.code);
                        paySign.push("package=prepay_id=" + ret.prepay_id);
                        paySign.push("signType=MD5");
                        paySign.push("timeStamp=" + n);
                        paySign.push("key=" + ret.key);
                        let _paySign = md5(paySign.join("&")).toUpperCase();
                        callback({
                            id: data.id,
                            actualAmount: data.actualAmount,
                            subAppId: ret.sub_appid,
                            appId: ret.appid,
                            timestamp: n,
                            nonceStr: data.code,
                            signature: str,
                            signType: 'MD5',
                            paySign: _paySign,
                            package: "prepay_id=" + ret.prepay_id
                        }, global.config.permission.private, response);
                    });
                } else {
                    callback({
                        code: ret.return_msg
                    });
                }
            });
        });
        //给推荐人发红包
        global.tool.send({
            method: 'get',
            uri: api.get('34bdca6ef71192487f48dc2g5ff2f951').replace("{id}",req.query.id)
        },function (error,response,body) {
            console.log(body.total);
            if(parseInt(body.total) === 1){   //第一次的情况下发红包
                global.tool.send({
                    method: 'get',
                    uri: api.get('1e1eb762896c418e8f8d72003dec8f40').replace("{id}", req.query.id)
                }, function (error, response, body) {
                    let data1 = (body && body.value) || {};
                    console.log('-------------data1-------------');
                    console.log(data1);
                    global.tool.send({
                        method:'get',
                        uri:api.get('5b90151b418f4ceb9469a6b265b0d617').replace("{id}",data1.properties.user.id)
                    },function (error,response,body) {
                        let userData = (body && body.value) || {};
                        let i=0;
                        let flag=true;
                        let discount=0.1;
                        let callbackFunc=function (userData) {
                            if(userData.introducer != ''){
                                global.tool.send({
                                    method: 'get',
                                    uri: api.get('44401b29a8b64ec19316bb651ecfbcb5').replace("{introducer}", userData.introducer)
                                }, function (error, response, body) {
                                    if (error) {
                                        console.log("----------error-----------");
                                        console.log(error);
                                    }
                                    console.log("----------IntroduceData-----------");
                                    let data = (body && body.value) || {};
                                    console.log("----------data-----------");
                                    console.log(data);
                                    global.weChatUtil.sendLuckyMoney({
                                        nonce_str: data.code,
                                        re_openid: data.weChat,
                                        siteId: 'mine',
                                        actualAmount:data1.properties.bill.actualAmount * discount * 100
                                    }, function (ret) {
                                        if (ret.return_code === 'SUCCESS') {
                                            console.log(ret);  //返回成功
                                            i++;
                                            switch (i){
                                                case 1:
                                                    discount=0.02;
                                                    break;
                                                case 2:
                                                    discount=0.01;
                                                    break;

                                            }
                                            if(i<3){           //10% 2% 1%
                                                callbackFunc(data);
                                            }
                                            return true;
                                        } else {
                                            console.log(ret);  //返回失败，查看失败原因
                                            callback({
                                                code: ret.return_msg
                                            });
                                        }
                                    });
                                })
                            }else{
                                flag=false;
                            }
                        }
                        if(flag && i==0){
                            callbackFunc(userData);
                        }
                    })
                });
            }
        })
    },
    //短租订单支付
    wepayShort: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('e42ad9a6eb584b5c88cbdfa00ee72e41').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            global.weChatUtil.preOrder({
                nonce_str: data.code,
                amount: data.rentPrice,
                remoteIp: req.get('X-Real-IP') || req.get('x-real-ip'),
                openid: req.session.userData.weChat,
                siteId: 'mine'
            }, function (ret) {
                if (ret.return_code === 'SUCCESS') {
                    global.weChatUtil.getTicket(function (ticket) {
                        let key = [], n = new Date().getTime();
                        key.push("jsapi_ticket=" + ticket);
                        key.push("noncestr=" + data.code);
                        key.push("timestamp=" + n);
                        key.push("url=http://" + SERVER_URL + "/view/order/wepay?id=" + data.id);
                        let str = sha1(key.join("&"));
                        let paySign = [];
                        paySign.push("appId=" + ret.appid);
                        paySign.push("nonceStr=" + data.code);
                        paySign.push("package=prepay_id=" + ret.prepay_id);
                        paySign.push("signType=MD5");
                        paySign.push("timeStamp=" + n);
                        paySign.push("key=" + ret.key);
                        let _paySign = md5(paySign.join("&")).toUpperCase();
                        callback({
                            id: data.id,
                            rentPrice: data.rentPrice,
                            subAppId: ret.sub_appid,
                            appId: ret.appid,
                            timestamp: n,
                            nonceStr: data.code,
                            signature: str,
                            signType: 'MD5',
                            paySign: _paySign,
                            package: "prepay_id=" + ret.prepay_id
                        }, global.config.permission.private, response);
                    });
                } else {
                    callback({
                        code: ret.return_msg
                    });
                }
            });
        });
    },

    repairCall: function (req, res, callback, next) {
        let timestamp = Date.parse(new Date()),
            t = timestamp / 1000, data = {};

        let url = "url=http://" + SERVER_URL + "/yams/view/repairCall?openId=" + req.query.openId;
        global.weChatUtil.getTicket(function (ticket) {
            let key = [];
            key.push("jsapi_ticket=" + ticket);
            key.push("noncestr=a" + t);
            key.push("timestamp=" + t);
            key.push(url);
            let str = sha1(key.join("&"));
            console.log(key.join("&"), str);
            extend(true, data, {
                appId: global.weChatUtil.config.appid,
                timestamp: t,
                nonceStr: "a" + t,
                signature: str
            });
            callback(data, global.config.permission.private);
        });
    },


    addRepair: function (req, res, callback, next) {
        let timestamp = Date.parse(new Date()),
            t = timestamp / 1000, data = {};

        let url = "url=http://" + SERVER_URL + "/yams/view/addRepair?openId=" + req.query.openId;
        global.weChatUtil.getTicket(function (ticket) {
            let key = [];
            key.push("jsapi_ticket=" + ticket);
            key.push("noncestr=a" + t);
            key.push("timestamp=" + t);
            key.push(url);
            let str = sha1(key.join("&"));
            console.log(key.join("&"), str);
            extend(true, data, {
                appId: global.weChatUtil.config.appid,
                timestamp: t,
                nonceStr: "a" + t,
                signature: str
            });
            callback(data, global.config.permission.private);
        });
    },

    repairList: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('fcca1aa0e7554b2bb871d3a1b8a7df36'),
            json: {
                properties: {
                    issueUser: req.session.userData.id
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },
//获得具体的保修信息
    repairInfo: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('170448e0874143b392e55a9925d9638c').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.private, response);
        });
    },
//获得所有的保洁信息
    clean: function (req, res, callback, next) {
        global.tool.send({
            method: 'post',
            uri: api.get('6890bc6b84ec46b6a0669d716fa41b68'),
            json: {
                properties: {
                    issueUser: req.session.userData.id
                }
            }
        }, function (error, response, body) {
            let data = (body && body.rows) || [];
            callback(data, global.config.permission.private, response);
        });
    },

//获得具体的保洁信息
    cleanInfo: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('7f7edb234d90457b9208eba7277e8f0c').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.private, response);
        });
    },

    addClean: function (req, res, callback, next) {
        let timestamp = Date.parse(new Date()),
            t = timestamp / 1000, data = {};

        let url = "url=http://" + SERVER_URL + "/yams/view/addClean?openId=" + req.query.openId;
        global.weChatUtil.getTicket(function (ticket) {
            let key = [];
            key.push("jsapi_ticket=" + ticket);
            key.push("noncestr=a" + t);
            key.push("timestamp=" + t);
            key.push(url);
            let str = sha1(key.join("&"));
            console.log(key.join("&"), str);
            extend(true, data, {
                appId: global.weChatUtil.config.appid,
                timestamp: t,
                nonceStr: "a" + t,
                signature: str
            });
            callback(data, global.config.permission.private);
        });
    },

    bindAccount: function (req, res, callback, next) {
        if (req.query.id) {
            global.tool.send({
                method: 'get',
                uri: api.get('5b90151b418f4ceb9469a6b265b0d617').replace("{id}", req.query.id)
            }, function (error, response, body) {
                let data = (body && body.value) || {};
                callback(data, global.config.permission.private, response);
            });
        } else {
            callback({});
        }
    },

    idCardUpload: function (req, res, callback, next) {
        if (req.query.id) {
            global.tool.send({
                method: 'get',
                uri: api.get('5b90151b418f4ceb9469a6b265b0d617').replace("{id}", req.query.id)
            }, function (error, response, body) {
                let data = (body && body.value) || {};
                let url = "url=http://" + SERVER_URL + "/yams/view/idCardUpload?id=" + req.query.id;
                let t = new Date().getTime();
                global.weChatUtil.getTicket(function (ticket) {
                    let key = [];
                    key.push("jsapi_ticket=" + ticket);
                    key.push("noncestr=a" + t);
                    key.push("timestamp=" + t);
                    key.push(url);
                    let str = sha1(key.join("&"));
                    console.log(key.join("&"), str);
                    callback({
                        appId: global.weChatUtil.config.appid,
                        timestamp: t,
                        nonceStr: "a" + t,
                        signature: str,
                        id: data.id,
                        idCardPhoto: data.idCardPhoto
                    }, global.config.permission.private, response);
                });
            });
        } else {
            callback({});
        }
    },

    shortRentList: function (req, res, callback, next) {

        if (req.query.groupFlag) {

            var condition = {};
            if (req.query.location) {
                condition.apartment_city_obj_ae = req.query.location;
            }
            if (req.query.houseType) {
                condition.houseType = req.query.houseType;
            }
            global.tool.send({
                method: 'post',
                uri: api.get('557583907a244d1d90fc237c70d3c25d'),
                json: {
                    properties: condition
                }
            }, function (error, response, body) {
                let row = (body && body.rows) || [];
                let data = {houseList: row};
                data.condition = {
                    location: req.query.location || '',
                    houseType: req.query.houseType || ''
                };

                Promise.all(global.tool.getEnumsByCodes(['cityList', 'houseType'])).then(function (resDate) {
                    var result = global.tool.extend(data, global.tool.extend({cityList: resDate[0]}, {houseType: resDate[1]}));
                    callback(result, global.config.permission.public, response);
                });

            });
        } else {
            global.tool.send({
                method: 'post',
                uri: api.get('9651431c68a04d54a22f1e2e7faf827b'),
                json: {
                    properties: {
                        apartment_city_obj_ae: req.query.city || '001',
                        status: 1,
                        pageSize: 50
                    }
                }
            }, function (error, response, body) {
                let row = (body && body.rows) || [];
                let data = {houseList: row};
                data.condition = {
                    location: req.query.location || '',
                    houseType: req.query.houseType || '',
                };
                callback(data, global.config.permission.public, response);
            });
        }


    },
    shortRentDetail: function (req, res, callback, next) {
        if (req.query.groupFlag) {
            global.tool.send({
                method: 'get',
                uri: api.get('0ce999a04d57409f8abd6297ece1fefg') + '?houseType=' + req.query.houseType + '&apartmentCity=' + req.query.apartmentCity
            }, function (error, response, body) {
                let data = (body && body.value) || {};

                /*let url = "url=http://" + SERVER_URL + "/yams/view/shortRentDetail?groupFlag=" + req.query.groupFlag+"&apartmentCity="+req.query.apartmentCity+"&houseType="+req.query.houseType;
                let t = new Date().getTime();
                global.weChatUtil.getTicket(function (ticket) {
                    let key = [];
                    key.push("jsapi_ticket=" + ticket);
                    key.push("noncestr=a" + t);
                    key.push("timestamp=" + t);
                    key.push(url);
                    let str = sha1(key.join("&"));
                    console.log(key.join("&"), str);
                    extend(data, {
                        appId: global.weChatUtil.config.appid,
                        timestamp: t,
                        nonceStr: "a" + t,
                        signature: str
                    });
                    callback(data, global.config.permission.private, response);
                });*/
                let timestamp = Date.parse(new Date()),
                    t = timestamp / 1000;

                let url = "url=http://" + SERVER_URL + "/yams/view/shortRentDetail?groupFlag=" + req.query.groupFlag+"&apartmentCity="+req.query.apartmentCity+"&houseType="+req.query.houseType+"&openId="+req.query.openId;
                global.weChatUtil.getTicket(function (ticket) {
                    let key = [];
                    key.push("jsapi_ticket=" + ticket);
                    key.push("noncestr=a" + t);
                    key.push("timestamp=" + t);
                    key.push(url);
                    let str = sha1(key.join("&"));
                    console.log(key.join("&"), str);
                    extend(true, data, {
                        appId: global.weChatUtil.config.appid,
                        timestamp: t,
                        nonceStr: "a" + t,
                        signature: str
                    });
                    callback(data, global.config.permission.private);
                });
            });
        } else {
            global.tool.send({
                method: 'get',
                uri: api.get('319bc41c5fe44dfc9f396b5ace5faf4a').replace("{id}", req.query.id)
            }, function (error, response, body) {
                let data = (body && body.value) || {};
                callback(data, global.config.permission.public, response);
            });
        }

    },
    shortRentReserved: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('319bc41c5fe44dfc9f396b5ace5faf4a').replace("{id}", req.query.houseId)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            callback(data, global.config.permission.public, response);
        });
    },
    shortRentOrder: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('e42ad9a6eb584b5c88cbdfa00ee72e41').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            console.log(data);
            callback(data, global.config.permission.public, response);
        });
    },

    butlerFix: function (req, res, callback, next) {
        let data = {
            properties: Object.assign({
                status: '1',         //1待处理
                                     //5
            }, req.query),
            list: []
        };
        callback(data, null, null)
        /*global.tool.send({
         method: 'post',
         uri: api.get('fcca1aa0e7554b2bb871d3a1b8a7df36'),
         json:data,
         }, (error, response, body) => {
         // let data = (body && body.value) || {};
         console.log(body);
         if(body.success){
         data.list = body.rows;
         }
         callback(data, global.config.permission.public, response);
         });*/
    },
    butlerBill: function (req, res, callback, next) {
        let data = {
            properties: Object.assign({
                status: '0',         //0待处理
                                     //1
            }, req.query),
            list: []
        };
        callback(data, null, null)
    },
    userEdit: function (req, res, callback, next) {
        global.tool.send({
            method: 'get',
            uri: api.get('5b90151b418f4ceb9469a6b265b0d617').replace("{id}", req.query.id)
        }, function (error, response, body) {
            let data = (body && body.value) || {};
            console.log(data);



            callback(data, global.config.permission.public, response);
        });
    },
    butlerClean: function (req, res, callback, next) {
        /*    let data = {
         condition: Object.assign({
         state: 'unfinished',
         }, req.query),
         list: [{
         id: '1',
         type: '整家清洁',
         time: '2017-05-05 16:50:23',
         house: {
         id: '1',
         address: 'A公寓604室',
         primaryImage: '',
         },
         state: '待处理',
         processedUser: '',
         processedTime: '',
         cost: '',
         remark: '',
         }]
         };
         callback(data, null, null);*/

        let data = {
            properties: Object.assign({
                status: '1',         //1待处理
                                     //5
            }, req.query),
            list: []
        };
        global.tool.send({
            method: 'post',
            uri: api.get('6890bc6b84ec46b6a0669d716fa41b68'),
            json: data,
        }, (error, response, body) => {
            // let data = (body && body.value) || {};
            if (body.success) {
                data.list = body.rows;
            }
            callback(data, global.config.permission.public, response);
        });
    },
    butlerBook: function (req, res, callback, next) {
        /*let data = {
         condition: Object.assign({
         state: 'created',
         }, req.query),
         list: [{
         id: '1',
         time: '2017-05-05 16:50:23',
         house: {
         id: '1',
         address: 'A公寓604室',
         houseType: '一居室',
         primaryImage: '',
         },
         state: 'created',
         bookUser: {
         id: '',
         name: '王小明',
         tel: '13800000000',
         },
         remark: '',
         }]
         };*/
        /*    <option value="IOS00">预约中</option>
         <option value="IOS01">已确认</option>
         <option value="IOS02">已看房</option>*/
        let data = {
            condition: {
                properties: Object.assign({
                        orderStatus: 'IOS00'
                    }
                    , req.query),
                list: []
            }

        };
        ;
        global.tool.send({
            method: 'post',
            uri: api.get('00923c89a610415d8e70b1b4f2380e75'),
            json: data.condition,
        }, (error, response, body) => {
            // let data = (body && body.value) || {};
            if (body.success) {
                data.list = body.rows;
            }

            Promise.all(global.tool.getEnumsByCodes(['inspectionOrderStatus'])).then(function (redData) {
                var result = global.tool.extend(data, {inspectionOrderStatus: redData[0]});
                callback(result, global.config.permission.public, response);
            });

        });

    },
    butlerInstrument: function (req, res, callback, next) {


        let data = {
            condition: {
                /*         state: 'unfinished',
                 month: global.tool.dateFormatter(new Date(), 'yyyy-MM'),*/
                properties: Object.assign({
                    status: 1,
                    month: global.tool.dateFormatter(new Date(), 'yyyy-MM'),
                }, req.query),

            },
            list: [/*{
             id: '1',
             state: 'unfinished',
             last:{
             time: '2017-05',
             water: '10',
             power: '20',
             gas: '30',
             },
             house: {
             id: '1',
             name: '舒适一室一厅',
             address: 'A公寓604室',
             houseType: '一居室',
             primaryImage: '',
             },
             water: '',
             power: '',
             gas: '',
             }*/]
        };

        let time = data.condition.properties.month;
        let meterYear = time.split('-')[0];
        let meterMon = parseInt(time.split('-')[1]);
        let status = data.condition.properties.status;
        global.tool.send({
            method: 'post',
            uri: api.get('ae5b4154f12b4ad5a074eaefec306131'),
            json: {
                "properties": {

                    "filterFlag": status,  //0 all              1 daichuli

                    "meterMonth": meterMon + '',

                    "meterYear": meterYear + '',

                    "pageNumber": 0,

                    "pageSize": 9999,

                    "status": 1
                }
            }
        }, (error, response, body) => {
            // let data = (body && body.value) || {};
            console.log(body);
            if (body.success) {
                data.list = body.rows;
                for (let i = 0; i < data.list.length; i++) {
                    console.log(data.list[i]);
                    console.log('------');

                }
            }
            callback(data, global.config.permission.public, response);
        });
    },
    butlerHouse: function (req, res, callback, next) {
        let data = {
            condition: Object.assign({
                searchStr: '',
                status: '',
                payLimit: '',
                checkoutLimit: '',
            }, req.query),
            list: []
        };

        Promise.all(global.tool.getEnumsByCodes(['houseStatus'])).then(function (resData) {
            var result = global.tool.extend(data, {houseStatus: resData[0]});
            callback(result, null, null);
        });


        // let condition = {};
        // if(data.condition.searchStr){
        //     condition.searchStr = data.condition.searchStr;
        // }
        // if(data.condition.status != 'all'){
        //     condition.status = data.condition.status;
        // }
        // if(data.condition.payLimit != 'all'){
        //     condition.payLimit = formatterTimeCondition(data.condition.payLimit);
        // }
        // if(data.condition.checkoutLimit != 'all'){
        //     condition.checkoutLimit = formatterTimeCondition(data.condition.checkoutLimit);
        // }
        //
        //
        // global.tool.send({
        //     method: 'post',
        //     uri: api.get('4567d53c166340f8a4194b8c5accc412'),
        //     json: condition
        // }, (error, response, body) => {
        //     // let data = (body && body.value) || {};
        //     if(body.success){
        //         data.list = body.rows;
        //     }
        //
        // });
    },
    butlerContract: function (req, res, callback, next) {

        /*   let data = {
         id: '1',
         name: '奢华一室',
         houseNo: '房号',
         houseType: '房型',
         bedType: '床型',
         price: '5000',
         state: 'empty',

         contract: {
         id: '2',
         code: '20170712001',
         price: '5000',
         deposit: '5000',
         activeTime: '2017-05-02',
         expireTime: '2018-05-02',
         payCycle: '三月一付',

         initWater: '1023',
         initPower: '231',
         initGas: '234',
         },
         user: {
         id: '3',
         code: '000004',
         name: '王小明',
         tel: '13800000000',
         cardNo: '620104199002120266'
         }
         };*/
        let contractId = req.query.id;
        let houseIds = req.query.houseId;

        let data = {
            houseId: houseIds
        };
        let pkid = req.query.pkid;

        if (contractId == 'undefined') {
            console.log(pkid);
            global.tool.send({
                method: 'get',
                uri: api.get('9651431c68a04d54a22f1e2e7faf827b') + '/' + pkid,
            }, (error, response, body) => {
                console.log(body);
                // let data = (body && body.value) || {};
                if (body.success) {
                    data = body.value;
                    Promise.all(global.tool.getEnumsByCodes(['houseType', 'bedType', 'payCycle'])).then(function (resData) {
                        var result = global.tool.extend(data, global.tool.extend({houseType: resData[0]},
                            global.tool.extend({bedType: resData[1]}, {payCycleArray: resData[2]})));
                        callback(result, global.config.permission.public, response);
                    });
                }
                ;
            });
        } else {
            global.tool.send({
                method: 'get',
                uri: api.get('509cb2a903d2466b9645432e025609c4') + '/' + contractId,
                json: {}
            }, (error, response, body) => {
                // let data = (body && body.value) || {};
                if (body.success) {
                    data = body.value;
                    data.status = 2;
                    Promise.all(global.tool.getEnumsByCodes(['houseType', 'bedType', 'payCycle'])).then(function (resData) {
                        var result = global.tool.extend(data, global.tool.extend({houseType: resData[0]},
                            global.tool.extend({bedType: resData[1]}, {payCycleArray: resData[2]})));
                        callback(result, global.config.permission.public, response);
                    });
                }

            });


        }

        /* $.ajax({
         type: "GET",
         url:  CTX + '/api/319bc41c5fe44dfc9f396b5ace5faf4a',
         data: {'id':id},
         dataType: "json",
         success: function(data){
         console.log(data);
         }
         });*/
    },
    butlerIndex: function (req, res, callback, next) {
        let data = {
            list: []
        };
        global.tool.send({
            method: 'post',
            uri: api.get('47b0ccc5194744dc89f5c17f40e0a5be'),
        }, (error, response, body) => {
            // let data = (body && body.value) || {};
            console.log(body);
            if (body.success) {
                data.list = body.value;

            }
            callback(data, global.config.permission.public, response);
        });

    },
};
//day_5 / month_1
function formatterTimeCondition(str) {
    let condition = str.split('_');
    let type = condition[0], n = condition[1];
    let now = new Date();
    let date;
    switch (type) {
        case 'day':
            date = new Date(now.getFullYear(), now.getMonth(), now.getDate() + n * 1);
            break;
        case 'month':
            date = new Date(now.getFullYear(), now.getMonth() + n * 1, now.getDate());
            break;
    }
    return global.tool.dateFormatter(date, 'yyyy-MM-dd');

}